//
//  PhotoSelectorViewController.swift
//  图片选择器
//
//  Created by x on 2017/7/20.
//  Copyright © 2017年 HLB. All rights reserved.
//

import UIKit
private let PhotoSelectorCellReuseIdentifier = "PhotoSelectorCellReuseIdentifier"
class PhotoSelectorViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        
        //初始化
        setupUI()
    }
    
    /// 初始化
    func setupUI() -> Void {
        
        //1.添加子控件
        view.addSubview(collectionView)
        
        //2.布局子控件
        var cons = [NSLayoutConstraint]()
        
        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["collectionView":collectionView])
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[collectionView]-0-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["collectionView":collectionView])
        view.addConstraints(cons)
        
    }
    //MARK: -- 懒加载
    fileprivate lazy var collectionView:UICollectionView = {
        let clv = UICollectionView(frame: CGRect.zero, collectionViewLayout: PhotoSelectorLayout())
        clv.translatesAutoresizingMaskIntoConstraints = false
        clv.dataSource =  self
        clv.register(PhotoSelectorCollectionViewCell.self, forCellWithReuseIdentifier: PhotoSelectorCellReuseIdentifier)
        
        return clv
    }()
    
    lazy var pictreImages = [UIImage]()
}

extension PhotoSelectorViewController:UICollectionViewDataSource,PhotoSelectorCollectionViewCellDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictreImages.count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let  cell = collectionView.dequeueReusableCell(withReuseIdentifier: PhotoSelectorCellReuseIdentifier, for: indexPath) as! PhotoSelectorCollectionViewCell
        cell.delegate = self
        /*
        count =2
        indexPath.item = 0
            
         count =2
         indexPath.item = 1
         
         //数组只有两张图片 但是 应为加1所有这个方法会多走一次
         count =2
         indexPath.item = 2
         */
        cell.image = (pictreImages.count == indexPath.item) ? nil : pictreImages[indexPath.item]
        
        return cell
    }
    
    
    /// 添加选中图片
    func photoDidAddSelector(cell: PhotoSelectorCollectionViewCell) {
        //1.判断设备支不支持这个格式
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
            //2.model出照片选择控制器
            let ipc = UIImagePickerController()
            ipc.delegate = self
            //设置相片是否可以编辑 编辑得到的相片都是正方形  方便我们可以设置为圆形
            ipc.allowsEditing = true
            //设置图片来源是相册
            ipc.sourceType = UIImagePickerControllerSourceType.photoLibrary
            present(ipc, animated: true, completion: nil);
        }else {
            print("不能打开相册")
        }
    }
    
    /// 删除选中图片
    func photoDidRemoveSelector(cell: PhotoSelectorCollectionViewCell) {
        
        //1.取得你点击的cell的位置
        let indexPath = collectionView.indexPath(for: cell)
        
        //2删除数组中的数据
        pictreImages.remove(at: indexPath!.item)
        
        //3.刷新表格
        collectionView.reloadData()
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //print(info)
        //1.取到我们选择的图片
        let image = info[UIImagePickerControllerEditedImage] as! UIImage
        /*
         一般情况下,只要涉及到从相册中获取图片的功能,都需要处理内存
         一般情况下一个引用程序启动会占用20M左右的内存,当内存飙升到500M的时候
         会发送内存警告,此时需要释放内存,否则就会闪退
         只要内存释放放到100M左右,那么系统就不会闪退我们的应用程序
         也就是说一个应用程序占用内存20-100M的时是比较安全的内存范围
         */
        //这里存在内存问题(图片太大了)
        //2.把图片加到数组中
        let newImage = image.imageWithWidth(width: UIScreen.main.bounds.width)
        
        pictreImages.append(newImage)
        //注意:1.通过这个方法压缩图片,图片压缩之后是不保针的
        //2. 苹果官方是不推荐我们使用JPG的图片的,因为JPG的图片解压缩的时候非常消耗性能
        //UIImageJPEGRepresentation(<#T##image: UIImage##UIImage#>, <#T##compressionQuality: CGFloat##CGFloat#>)
        //建议通过等比缩放的来实现图片的压缩
        //3.刷新视图
        collectionView.reloadData()
        
        //4.关闭图片选择器
        dismiss(animated: true, completion: nil)
    }
}

class PhotoSelectorLayout: UICollectionViewFlowLayout {
    override func prepare() {
        super.prepare()
        
        //1.设置item的属性
        itemSize = CGSize(width: 80, height: 80)
        minimumLineSpacing = 10
        minimumInteritemSpacing = 10
        sectionInset = UIEdgeInsetsMake(20, 10, 0, 10)
    }
}

protocol PhotoSelectorCollectionViewCellDelegate:NSObjectProtocol {
    
    /// 添加选中图片
    func photoDidAddSelector(cell: PhotoSelectorCollectionViewCell)
    
    /// 删除选中图片
    func photoDidRemoveSelector(cell: PhotoSelectorCollectionViewCell)
}
class PhotoSelectorCollectionViewCell: UICollectionViewCell {
    
    /// 代理对象
    weak var delegate:PhotoSelectorCollectionViewCellDelegate?
    
    /// 按钮图片
    var image:UIImage? {
        didSet {
            if image == nil {
                addButton.isUserInteractionEnabled = true
                removeButton.isHidden = true
                addButton.setBackgroundImage(UIImage.init(named: "compose_pic_add"), for: UIControlState.normal)
                addButton.setBackgroundImage(UIImage.init(named: "compose_pic_add_highlighted"), for: UIControlState.highlighted)
            }else {
                addButton.isUserInteractionEnabled = false
                removeButton.isHidden = false
                addButton.setBackgroundImage(image, for: UIControlState.normal)
                addButton.setBackgroundImage(nil, for: UIControlState.highlighted)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //1.添加子控件 
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
        
        //2.布局子控件
        var  cons = [NSLayoutConstraint]()
        
        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[addButton]-0-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["addButton":addButton])
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[addButton]-0-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["addButton":addButton])
        
        cons += NSLayoutConstraint.constraints(withVisualFormat: "H:[removeButton]-2-|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["removeButton":removeButton])
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-2-[removeButton]", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["removeButton":removeButton])
        
        contentView.addConstraints(cons)
        
    }
    
    /// 增加按钮点击事件
    func addButtonClick() -> Void {
        delegate?.photoDidAddSelector(cell: self)
    }
    
    /// 移除按钮点击事件
    func removeButtonClick() -> Void {
        delegate?.photoDidRemoveSelector(cell: self)
    }
    //MARK: -- 懒加载
    
    private lazy var addButton:UIButton = {
        let tt = UIButton()
        tt.translatesAutoresizingMaskIntoConstraints = false
        tt.setBackgroundImage(UIImage.init(named: "compose_pic_add"), for: UIControlState.normal)
        tt.setBackgroundImage(UIImage.init(named: "compose_pic_add_highlighted"), for: UIControlState.highlighted)
        tt.addTarget(self, action: #selector(addButtonClick), for: UIControlEvents.touchUpInside)
        
        return tt
    }()
    
    private lazy var removeButton:UIButton = {
        let tt = UIButton()
        tt.isHidden = true
        tt.translatesAutoresizingMaskIntoConstraints = false
        tt.setBackgroundImage(UIImage.init(named: "compose_photo_close"), for: UIControlState.normal)
        tt.addTarget(self, action: #selector(removeButtonClick), for: UIControlEvents.touchUpInside)
        
        return tt
    }()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}









